const http = require('http')
const fs = require('fs')
var url = require('url')
var toPdf = require("office-to-pdf")
const JSZip = require('pizzip')
const Docxtemplater = require('docxtemplater')
const ImageModule = require('docxtemplater-image-module-free')
var path = require('path')
const https = require("https")
const Stream = require("stream").Transform

const server = http.createServer((req, res) => {
    if (req.url === '/index.html') {
        const path = require('path')
        fs.readFile(path.join(__dirname, './index.html'), (err, data) => {
            res.writeHead(200, {
                'Content-Type': 'text/html'
            })
            res.write(data.toString())
            res.end()
        })
    }

    if (req.url.includes('/login')) {
        var content = fs.readFileSync(path.join(__dirname, './template/template1.docx'), 'binary')
        var zip = new JSZip(content)
        var doc = new Docxtemplater()

        const opts = {
            getImage(tagValue, tagName) {
                // tagValue is "https://docxtemplater.com/xt-pro-white.png" and tagName is "image"
                return new Promise(function (resolve, reject) {
                    getHttpData(tagValue, function (err, data) {
                        if (err) {
                            return reject(err)
                        }
                        resolve(data);
                    })
                })
            },
            getSize(img, tagValue, tagName) {
                // console.log(tagValue, tagName);
                // // img is the value that was returned by getImage
                // // This is to force the width to 600px, but keep the same aspect ration
                // const sizeOf = require("image-size");
                // const sizeObj = sizeOf(img);
                // console.log(sizeObj);
                // const forceWidth = 600;
                // const ratio = forceWidth / sizeObj.width;
                // return [
                //     forceWidth,
                //     // calculate height taking into account aspect ratio
                //     Math.round(sizeObj.height * ratio),
                // ];
                return [150, 50];
            }
        }
        doc.attachModule(new ImageModule(opts))
        doc.loadZip(zip).compile()

        var query = url.parse(req.url, true).query
        var data = {
            // name: query.name,
            // ptGender: query.ptGender,
            // age: query.age,
            // diagnosisNo: query.diagnosisNo,
            // sendDepartment: query.sendDepartment,
            // badNo: query.badNo,
            // grossDescript: query.grossDescript,
            name: 1,
            ptGender: 1,
            age: 1,
            diagnosisNo: 1,
            sendDepartment: 1,
            badNo: 1,
            grossDescript: 1,
            description: '13957162439139571624391395716243911395716243913957162439139571624391395716243913957162439113957162439139571624391395716243913957162439139571624391139571624391395716243913957162439139571624391395716243911395716243913957162439139571624391395716243913957162439113957162439139571624391395716243913957162439139571624391139571624391395716243913957162439139571624391395716243911395716243913957162439139571624391395716243913957162439113957162439139571624391395716243913957162439139571624391139571624391395716243913957162439139571624391395716243911395716243913957162439139571624391395716243913957162439113957162439139571624391395716243913957162439139571624391139571624391395716243913957162439139571624391395716243911395716243913957162439139571624391395716243913957162439113957162439139571624391395716243913957162439139571624391139571624391395716243913957162439139571624391395716243911395716243913957162439139571624391395716243913957162439113957162439139571624391395716243913957162439139571624391139571624391395716243913957162439139571624391395716243911395716243913957162439',
            list: [
                {
                    image1: query.image,
                    desc1: '123',
                    image2: query.image,
                    desc2: '123',
                },
                {
                    image1: query.image,
                    desc1: '123',
                    image2: query.image,
                    desc2: '123',
                },
                {
                    image1: query.image,
                    desc1: '123',
                    image2: query.image,
                    desc2: '123',
                },
            ]
        }

        doc.resolveData(data).then(async () => {
            doc.render()
            let wordBuffer = doc.getZip().generate({ type: 'nodebuffer' })
            let date = new Date().getTime()
            // 写word
            // let file = path.resolve(__dirname, `report/output-${date}.docx`)
            // fs.writeFileSync(file, wordBuffer)
            let pdfBuffer = await toPdf(wordBuffer).catch(err => console.log(err))
            fs.writeFileSync(path.resolve(__dirname, `report/output-${date}.pdf`), pdfBuffer)
            console.log('报告已生成')
            res.end('报告已生成')
        }).catch(function (error) {
            console.log('生成报告失败', error)
            res.end('生成报告失败')
        })
    }
})

server.listen(8000, () => {
    console.log('启动成功！')
})

function getHttpData(imageUrl, callback) {
    https.request(imageUrl, function (response) {
        if (response.statusCode !== 200) {
            return callback(
                new Error(
                    `Request to ${url} failed, status code: ${response.statusCode}`
                )
            );
        }

        const data = new Stream()

        response.on("data", function (chunk) {
            data.push(chunk)
        })

        response.on("end", function () {
            callback(null, data.read())
        })

        response.on("error", function (e) {
            callback(e)
        })
    }).end()
}
